//
//  YpViewController.m
//  KIASupervisory
//
//  Created by apple on 15/7/19.
//  Copyright (c) 2015年 MyCompany. All rights reserved.
//

#import "YpViewController.h"
#import "TongzhiViewController.h"
#import "MainViewController.h"
#import "YoukeViewController.h"

@interface YpViewController ()

@property (nonatomic, strong) NSMutableArray *ypList;
@property (nonatomic, strong) UIButton *back;
@property (nonatomic, strong) NetworkManager *networkManager;
@property (nonatomic, strong) MBProgressHUD *HUD;
@property (retain, nonatomic) IBOutlet UITableView *tableView;
@property (retain, nonatomic) IBOutlet UISearchBar *searchBar;
@property (nonatomic, assign) NSInteger selectedRow;

@end

@implementation YpViewController

@synthesize dataList = _dataList;
@synthesize showData = _showData;

- (void)viewDidLoad
{
    [self.navigationController setNavigationBarHidden:YES];
    [super viewDidLoad];
    self.ypList = [NSMutableArray array];
    _tableView.frame  = CGRectMake(0, 70, self.view.frame.size.width, self.view.frame.size.height-70);
    [[self view] addSubview:[self tableView]];
    self.networkManager = [[NetworkManager alloc] init];
    self.HUD = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:self.HUD];
    self.HUD.delegate = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

}

- (IBAction)backToPre:(id)sender {
    UserInfo *user = [UserInfo instance];
    CATransition* transition = [CATransition animation];
    transition.type = kCATransitionPush;//可更改为其他方式
    transition.subtype = kCATransitionFromRight;//可更改为其他方式
    if(user.info != nil){
        MainViewController *problemVC = (MainViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"MainViewController"];

        [self.navigationController.view.layer addAnimation:transition forKey:kCATransition];
        [self.navigationController pushViewController:problemVC animated:NO];
    } else {
        YoukeViewController *problemVC = (YoukeViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"YoukeViewController"];
                
        [self.navigationController.view.layer addAnimation:transition forKey:kCATransition];
        [self.navigationController pushViewController:problemVC animated:NO];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    [self performSelector:@selector(getWzList) withObject:nil afterDelay:0.3];
}

- (void)refreshViewByReloadData {
    [self getWzList];
}

- (void)getWzList {
    [self.ypList removeAllObjects];
    
    UserInfo *user = [UserInfo instance];
    if (self.networkManager == nil) {
        self.networkManager = [[NetworkManager alloc] init];
    }
    NSString *user_id= @"";
    
    NSString *xiaoqu_id = @"8";
    if(user.info != nil){
        user_id = [user.info objectForKey:@"user_id"];
        xiaoqu_id = [user.info objectForKey:@"xiaoqu_id"];
    }
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                           user_id,@"user_id",xiaoqu_id,@"xiaoqu_id", nil];
    [self.networkManager requestWithMethod:getYpById parameter:param delegate:self];
    [self.HUD show:YES];

}

#pragma mark - UITableViewDataSource methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.ypList count];
}

- (void)network:(NetworkManager *)net methodId:(RequestMethodId)methodId didRequestFinishedWithResult:(id)data {
    [self.HUD hide:YES];
    if (methodId == getYpById) {
        if ([data isKindOfClass:[NSDictionary class]]) {
            NSString * result = [data objectForKeyOrNil:@"result"];
            if([result isEqualToString:@"000"]){
                
                [self.ypList removeAllObjects];
                
                NSArray *results = [data objectForKeyOrNil:@"ypList"];
                if (![results isKindOfClass:[NSNull class]] && [results count] > 0) {
                    [self.ypList  addObjectsFromArray:results];
                }
                
                
                [self.tableView reloadData];
            } else if([result isEqualToString:@"001"]){
                NSString * resultinfo = [data objectForKeyOrNil:@"resultinfo"];
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                                message:[resultinfo stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]
                                                               delegate:nil
                                                      cancelButtonTitle:@"确定"
                                                      otherButtonTitles:nil];
                [alert show];
                
            }
        }
        
    } else if (methodId == searchYp){
        if ([data isKindOfClass:[NSDictionary class]]) {
            NSString * result = [data objectForKeyOrNil:@"result"];
            if([result isEqualToString:@"000"]){
                
                [self.ypList removeAllObjects];
                
                NSArray *results = [data objectForKeyOrNil:@"ypList"];
                if (![results isKindOfClass:[NSNull class]] && [results count] > 0) {
                    [self.ypList  addObjectsFromArray:results];
                }
                
                
                [self.tableView reloadData];
            } else if([result isEqualToString:@"001"]){
                NSString * resultinfo = [data objectForKeyOrNil:@"resultinfo"];
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                                message:[resultinfo stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]
                                                               delegate:nil
                                                      cancelButtonTitle:@"确定"
                                                      otherButtonTitles:nil];
                [alert show];
                
            }
        }
    }
    
}

- (void)network:(NetworkManager *)net methodId:(RequestMethodId)methodId didRequestFailedWithError:(NSError *)error {
    NSDictionary *errorInfo = error.userInfo;
    NSString *msg = [errorInfo objectForKeyOrNil:@"errorMsg"];
    
    NSInteger code = error.code;
    if (code != 1) {
        if ([msg length] == 0) {
            msg = @"数据获取失败，请稍后重试";
        }
    }
    if ([msg length] > 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:msg
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CategoryCell = @"CategoryCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:
                             CategoryCell];

    if (cell == nil) {
        cell = [[UITableViewCell alloc]
                initWithStyle:UITableViewCellStyleDefault
                reuseIdentifier:CategoryCell];
    }
    if (self.ypList != nil && self.ypList.count >0) {
        NSUInteger row = [indexPath row];
        UILabel *titleLbl = (UILabel *)[cell.contentView viewWithTag:101];
        UILabel *nameLbl = (UILabel *)[cell.contentView viewWithTag:102];
        UILabel *phoneLbl = (UILabel *)[cell.contentView viewWithTag:103];
        NSDictionary* dic = [self.ypList objectAtIndex:row];
        
        NSString *ypCategoryStr = [[dic objectForKey:@"ypCategory"] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSString *ypNameStr = [[dic objectForKey:@"ypName"] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        titleLbl.text = ypCategoryStr;
        nameLbl.text = ypNameStr;
        phoneLbl.text =[dic objectForKey:@"ypPhone"];
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSInteger row = indexPath.row;
    self.selectedRow = row;
    
    if ([self.ypList count] > row) {
        if ([self.ypList count] > row) {
            NSDictionary *wzInfo = [self.ypList objectAtIndex:row];
            NSString *phone = [wzInfo objectForKey:@"ypPhone"] ;
            NSString *num = [[NSString alloc]initWithFormat:@"telprompt://%@",phone]; //而这个方法则打电话前先弹框 是否打电话 然后打完电话之后回到程序中 网上说这个方法可能不合法 无法通过审核
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:num]];
        }
    }
}

-(void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [self searchBar:self.searchBar textDidChange:nil];
    UserInfo *user = [UserInfo instance];
    if (self.networkManager == nil) {
        self.networkManager = [[NetworkManager alloc] init];
    }
    NSString *xiaoqu_id = [user.info objectForKey:@"xiaoqu_id"];
    xiaoqu_id  = @"8";
    NSDictionary *param1 = [NSDictionary dictionaryWithObjectsAndKeys:
                           self.searchBar.text,@"search_content",
                           xiaoqu_id,@"xiaoqu_id", nil];
    
    [self.networkManager requestWithMethod:searchYp parameter:param1 delegate:self];
    [self.HUD show:YES];
    [_searchBar resignFirstResponder];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *) searchBar
{
    [self searchBar:self.searchBar textDidChange:nil];
    [_searchBar resignFirstResponder];
}


@end

